package org.caenv.interpreter.parser;

import java.util.HashMap;
import java.util.Map;
import org.caenv.interpreter.ExecutionException;

public class MemoryManager {

    private final Map<String, Object> variables;

    public MemoryManager () {
        variables = new HashMap<String, Object>();
    }
    
    public void addVariable(String name, Object value){
        this.variables.put(name, value);
    }
    
    public void setValue (String name, Object value) throws ExecutionException{
        if(this.variables.containsKey(name)){
            this.variables.put(name, value);
        }else{
            throw new ExecutionException(new Exception("Variable not found."));
        }
    }
    
    public Object getValue (String name) throws ExecutionException {
        
        if(name.startsWith("#")){
            
            if(this.variables.containsKey(name)){
                return this.variables.get(name);
            }else{
                throw new ExecutionException(new Exception("Variable not found."));
            }
            
        }else{
            
            try{
                
                if(name.contains(".")){
                    Double value = Double.parseDouble(name);
                    return value;
                }else{
                    Integer value = Integer.parseInt(name);
                    return value;
                }
                
            }catch(NumberFormatException e){
                return name;
            }
            
            
        }
        
    }
    
}
